package abaco.gui.textfield;

import java.awt.Color;

import javax.swing.BorderFactory;
import javax.swing.JTextField;
import javax.swing.border.Border;

import abaco.gui.textfield.listener.DocumentListener;
import abaco.gui.textfield.listener.FocusListener;
import abaco.gui.textfield.listener.KeyListener;
import abaco.gui.textfield.listener.MouseListener;

public abstract class TextField extends JTextField {
	protected Border defaultBorder = BorderFactory.createCompoundBorder(BorderFactory.createEmptyBorder(4, 4, 4, 4), new DashedBorder(Color.LIGHT_GRAY, 1));
	protected Border focusedBorder = BorderFactory.createCompoundBorder(BorderFactory.createEmptyBorder(4, 4, 4, 4), new DashedBorder(Color.BLACK, 1));
	public static Color defaultForeground = Color.BLACK;

	public TextField () {
		setup();
		setupListeners();
	}

	private void setup () {
		setForeground(defaultForeground);
		setHorizontalAlignment(CENTER);
		setBorder(defaultBorder);
		//setFont(abaco.gui.util.Font);
		autoColumns();
	}

	private void setupListeners() {
		getDocument().addDocumentListener(new DocumentListener(this));
		addFocusListener(new FocusListener(this));
		addKeyListener(new KeyListener(this));
		addMouseListener(new MouseListener(this));
	}

	/**
	 * Change text field to a comfortable width.
	 *
	 * Font is monospaced, colunsEdge means how many white characters must have
	 * exist at the beginning and end of the text. There is also a special
	 * treatment for empty text, in this case the edge is duplicated.
	 */
	public TextField autoColumns() {
		int length = getText().length();
		int edge = 0 == length ?  2 : 1;
		setColumns(length + edge);
		return this;
	}

	public Border getDefaultBorder() {
		return defaultBorder;
	}

	public Border getFocusedBorder() {
		return focusedBorder;
	}
}
